package com.xinchen.all.ui.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.huyuhui.fastble.data.BleDevice
import com.maple.utils.ext.layoutInflater
import com.xinchen.all.R

class BluetoothDeviceAdapter2(val context: Context): RecyclerView.Adapter<BluetoothDeviceAdapter2.ViewHolder>(){

    private val list = mutableListOf<BleDevice>()

    private var listener: OnClickListener? = null

    fun setListener(l: OnClickListener?) {
        listener = l
    }

    fun setData(l: List<BleDevice>?) {
        this.list.clear()
        l?.let {
            this.list.addAll(l)
        }
        this.notifyDataSetChanged()
    }

    fun addDevice(device: BleDevice?) {
        device?.let {
            list.add(device)
            this.notifyDataSetChanged()
        }
    }

    fun getDataList(): List<BleDevice> = list
    fun clear() {
        list.clear()
        this.notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view: View = context.layoutInflater.inflate(R.layout.item_bluetooth_device, parent, false)
        val holder: ViewHolder = ViewHolder(view)
        holder.itemRoot.setOnClickListener {
            listener?.onItemClick(
                holder.bindingAdapterPosition,
                list.get(holder.bindingAdapterPosition),
            )
        }
        return holder
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.setData(position,list.get(position))
    }

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {


        val itemRoot: LinearLayout = itemView.findViewById(R.id.item_root)
        private val tvName: TextView = itemView.findViewById(R.id.tv_name)

        fun setData(position: Int, device: BleDevice) {
            tvName.text = device.name
        }

    }

    interface OnClickListener {
        fun onItemClick(pos: Int = 0, device: BleDevice?)
    }

}